import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/token'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: () => import(/* webpackChunkName: "Login" */ '@/views/Login'),
    beforeEnter: (to, from, next) => {
      // ...已登录时进入登陆页面，直接跳转到首页
      const token = getToken() || ''
      if (token.length > 0) {
        next('/layout/home')
      } else {
        next()
      }
    }
  },
  {
    path: '/layout',
    component: () => import(/* webpackChunkName: "Home" */ '@/views/Layout'),
    redirect: '/layout/home',
    meta: { isAuth: true },
    children: [
      {
        path: 'home',
        component: () => import(/* webpackChunkName: "Home" */ '@/views/Home'),
        meta: {
          isAuth: true,
          scrollT: 0 // 滚动条位置, tabid:001, top:xx
        }
      }, {
        path: 'user',
        component: () => import(/* webpackChunkName: "User" */ '@/views/User'),
        meta: { isAuth: true }
      },
      {
        path: 'user_edit',
        component: () => import(/* webpackChunkName: "UserEdit" */ '@/views/User/components/UserEdit'),
        meta: { isAuth: true }
      }
    ]
  },
  {
    path: '/search',
    component: () => import(/* webpackChunkName: "Search" */ '@/views/Search'),
    meta: { isAuth: true }
  },
  {
    name: 'result',
    path: 'search_result/:kw',
    component: () => import(/* webpackChunkName: "SearchResult" */ '@/views/Search/SearchResult'),
    props: true,
    meta: { isAuth: true }
  },
  {
    path: '/article_detail',
    component: () => import(/* webpackChunkName: "ArticleDetail" */ '@/views/ArticleDetail'),
    props ($route) {
      return { aid: $route.query.aid }
    },
    meta: { isAuth: true }
  }
]

const router = new VueRouter({
  routes
})

// 全局前置路由拦截器
router.beforeEach((to, from, next) => {
  // 需要校验是否有token
  if (to.meta.isAuth) {
    if (getToken().length > 0) {
      next()
    } else {
      // 校验未通过，重新回到登陆页
      next({
        path: '/login'
      })
    }
  }
  // 不需要校验token（登陆页）直接放行
  next()
})

export default router
